package com.dp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dp.dto.Result;
import com.dp.dto.ScrollResult;
import com.dp.dto.UserDTO;
import com.dp.entity.Blog;
import com.dp.entity.Follow;
import com.dp.entity.User;
import com.dp.mapper.BlogMapper;
import com.dp.service.IBlogService;
import com.dp.service.IFollowService;
import com.dp.service.IUserService;
import com.dp.utils.SystemConstants;
import com.dp.utils.UserHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static com.dp.utils.RedisConstants.BLOG_LIKED_KEY;
import static com.dp.utils.RedisConstants.FEED_KEY;

/**
 * <p>
 * 服务实现类
 * </p>
 */
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private IUserService userService;

    @Resource
    private IFollowService followService;

    @Override
    public Result queryHotBlog(Integer current) {
        // 根据用户查询
        Page<Blog> page = query()
                .orderByDesc("liked")
                .page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        // 查询用户
//        records.forEach(this::queryBlogUser);
        records.forEach(blog -> {
            this.isBlogLiked(blog);
            this.queryBlogUser(blog);
        });

        return Result.ok(records);
    }


    //查询探店笔记
    @Override
    public Result queryBlogById(Long id) {
        // 1. 查询blog
        Blog blog = this.getById(id);
        if (blog == null) {
            return Result.fail("笔记不存在");
        }
        // 2. 查询blog 有关的用户
        queryBlogUser(blog);

        //3. 查询blog 是否被点过赞
        isBlogLiked(blog);
        return Result.ok(blog);
    }

    private void isBlogLiked(Blog blog) {
        UserDTO user = UserHolder.getUser();
        if (user == null) {
            //用户 未登入 无需查询是否点赞
            return;
        }
        //1.判断当前登入用户是否点赞
        Long userId = UserHolder.getUser().getId();
        //2. 判断当前登入用户是否已经点赞
        Double score = stringRedisTemplate.opsForZSet().
                score(BLOG_LIKED_KEY + blog.getId(), userId.toString());
        blog.setIsLike(score != null);
    }

    //点赞功能 一人一个赞
    @Override
    public Result likeBlog(Long id) {
        //1.判断当前登入用户是否点赞
        Long userId = UserHolder.getUser().getId();
        String key = BLOG_LIKED_KEY + id;
        //2. 判断当前登入用户是否已经点赞
        Double score = stringRedisTemplate.opsForZSet().score(BLOG_LIKED_KEY + id, userId.toString());
        if (score == null) {
            //3.如果未点赞可以点赞
            // 3.1 数据库点赞数+1
            boolean isSuccess = this.update().
                    setSql("liked = liked + 1").eq("id", id).update();
            // 3.2 保存用户到redis 的 set集合  后修改为sortedSet
            if (isSuccess) {       // zadd key value score
                stringRedisTemplate.opsForZSet().add(key, userId.toString(), System.currentTimeMillis());
            }
        } else {
            //4.如果已经点赞 取消点赞
            boolean isSuccess = this.update().
                    setSql("liked = liked - 1").eq("id", id).update();
            // 4.1 数据库点赞数-1
            // 4.2 redis 中set集合中移除
            if (isSuccess) {
                stringRedisTemplate.opsForZSet().remove(key, userId.toString());
            }
        }
        return Result.ok();
    }

    @Override
    public Result queryBlogLikes(Long id) {
        String key = BLOG_LIKED_KEY + id;
        //1. 查询top5的点赞用户 zrange key 0 4
        Set<String> top5 = stringRedisTemplate.opsForZSet().range(key, 0, 4);
        if (top5 == null || top5.isEmpty()) {
            return Result.ok(Collections.emptyList());
        }
        //2. 解析出其中的用户id
        List<Long> ids = top5.stream().map(Long::valueOf).collect(Collectors.toList());
        String join = StrUtil.join(",", ids);
        //3. 根据用户id查询用户 where id in (5,1) order by field(id , 5 ,1)
        List<UserDTO> collect = userService.query().in("id", id).
                last("order by field(," + join + ")").list().stream().
                map(user ->
                        BeanUtil.copyProperties(user, UserDTO.class))
                .collect(Collectors.toList());
        //4. 返回
        return Result.ok(collect);
    }

    /**
     * 推送到粉丝收件箱
     * @param blog
     * @return
     */
    @Override
    public Result saveBlog(Blog blog) {
        // 1.获取登录用户
        UserDTO user = UserHolder.getUser();
        blog.setUserId(user.getId());
        //2. 保存探店笔记
        boolean save = this.save(blog);
        if (!save){
            return Result.fail("新增笔记失败");
        }
        //3.查询笔记作者的所有粉丝  select * from tb_follow where follow_user_id =?
        List<Follow> follows = followService.
                query().eq("follow_user_id", user.getId()).list();

        //4.推送笔记id 给所有粉丝
        for (Follow follow : follows) {
            // 4.1 获得粉丝id
            Long userId = follow.getUserId();
            // 4.2 推送
            String key=FEED_KEY+userId;
            stringRedisTemplate.opsForZSet().add(key,blog.getId().toString(),System.currentTimeMillis());
        }
        //4.返回id
        return Result.ok(blog.getId());
    }

    // TODO  滚动分页查询邮箱
    @Override
    public Result queryBlogOfFollow(Long max, Integer offset) {
        //1. 获取当前用户
        Long userId = UserHolder.getUser().getId();
        //2. 查询收件箱   ZREVRANGEBYSCORE key Max Min LIMIT offset count
        String key=FEED_KEY+userId;
        Set<ZSetOperations.TypedTuple<String>> typedTuples = stringRedisTemplate.opsForZSet().
                reverseRangeByScoreWithScores(key, 0, max, offset, 2);
        if (typedTuples==null||typedTuples.isEmpty()){
            return Result.ok();
        }
        ArrayList<Long> ids = new ArrayList<>(typedTuples.size());
        long minTime=0;
        int os=1;
        //3. 解析数据 blogId , score(时间戳), offset(上次查询最小值的 个数有几个)
        for (ZSetOperations.TypedTuple<String> typedTuple : typedTuples) {
            String idStr = typedTuple.getValue();  //获取id
            ids.add(Long.valueOf(idStr));
            long time = typedTuple.getScore().longValue();//分数 时间戳  最小
            if (time==minTime){
                os++;
            }else {
                minTime=time;
                os=1;
            }
        }
//        os = minTime == max ? os : os + offset;
        //4. 根据id 查询blog
        String idStr = StrUtil.join(",", ids);
        List<Blog> blogs = this.query().in("id", ids).
                last("ORDER BY FIELD(id," + idStr + ")").list();
        for (Blog blog : blogs) {
            // 2. 查询blog 有关的用户
            queryBlogUser(blog);
            //3. 查询blog 是否被点过赞
            isBlogLiked(blog);
        }
        //5. 封装 为ScrollResult
        ScrollResult scrollResult = new ScrollResult();
        scrollResult.setList(blogs);
        scrollResult.setOffset(os);
        scrollResult.setMinTime(minTime);

        return Result.ok(scrollResult);
    }

    private void queryBlogUser(Blog blog) {
        Long userId = blog.getUserId();
        User user = userService.getById(userId);
        blog.setName(user.getNickName());
        blog.setIcon(user.getIcon());
    }
}
